﻿Imports System.Data.OleDb
Imports AjaxControlToolkit

Public Class QuizOverview
    Inherits System.Web.UI.Page

    Public commentIdBack As Int32

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try


            ltrCode.Text = ""
            ltrUsersLiked.Text = ""
            If (Not Page.IsPostBack) Then

                Dim webUrl As String = Request.Url.ToString()

                ltrFacebook.Text = " <div class=""fb-like"" data-href=""" + webUrl + """ data-send=""false"" data-width=""450"" data-show-faces=""true"" data-font=""arial""></div>"


                addVisitor()
                LikeRating.AutoPostBack = True

                Dim rating As Quiz_RatingManagement = New Quiz_RatingManagement()
                Dim currentRating As Double = rating.SelectAVGQuizRatingByQuizId(Request.QueryString("quizId"))

                LikeRating.CurrentRating = Math.Round(currentRating)

                Dim myQuiz As QuizManagement = New QuizManagement()
                Dim dr As OleDbDataReader = myQuiz.SelectQuizByQuizId(Request.QueryString("quizId"))

                If dr.HasRows Then
                    Do While dr.Read()
                        If Not IsDBNull(dr("QuizName")) Then lblQuizName.Text = (dr("QuizName"))
                        If Not IsDBNull(dr("QuizDescription")) Then lblQuizDescription.Text = (dr("QuizDescription"))
                        If Not IsDBNull(dr("QuizPicture")) Then imgQuiz.ImageUrl = (dr("QuizPicture"))
                    Loop
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub addVisitor()
        Try

            Dim aCookie As HttpCookie = Request.Cookies("userIdCookie")
            Dim userId = Convert.ToInt32(aCookie.Value)

            Dim pageName As String = Request.Url.PathAndQuery
            pageName = pageName.Replace("/", "")

            Dim getPageNameId As PagesNamesManagement = New PagesNamesManagement()
            Dim dr As OleDbDataReader = getPageNameId.SelectPagesNamesByPageNameContent(pageName)

            Dim pageId As Int32 = -1

            If dr.HasRows Then
                dr.Read()
                If Not IsDBNull(dr("PageNameId")) Then pageId = Convert.ToInt32(dr("PageNameId"))
            End If


            If (pageId <> -1) Then

                Dim insertUser As User_PagesNameManagement = New User_PagesNameManagement()
                insertUser.InsertUserPageName(userId, pageId)

            End If

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub LikeRating_Changed(ByVal sender As Object, ByVal e As RatingEventArgs)
        Try

        
        Dim selectedRating As Int32 = Convert.ToInt32(e.Value)

        Dim aCookie As HttpCookie = Request.Cookies("userIdCookie")
        Dim userId = Convert.ToInt32(aCookie.Value)

        Dim myQuizRating As Quiz_RatingManagement = New Quiz_RatingManagement()

        If (myQuizRating.SelectCountUserIdQuizId(userId, Convert.ToInt32(Request.QueryString("QuizId"))) = 0) Then
            Dim myQuizRating2 As Quiz_RatingManagement = New Quiz_RatingManagement()
            myQuizRating2.InsertQuizRating(selectedRating, Convert.ToInt32(Request.QueryString("QuizId")), userId)
        Else

            Dim myQuizRating3 As Quiz_RatingManagement = New Quiz_RatingManagement()
            myQuizRating3.DeleteQuizRatingByQuizIdUserId(Convert.ToInt32(Request.QueryString("QuizId")), userId)

            Dim myQuizRating4 As Quiz_RatingManagement = New Quiz_RatingManagement()
            myQuizRating4.InsertQuizRating(selectedRating, Convert.ToInt32(Request.QueryString("QuizId")), userId)
        End If



        Dim rating As Quiz_RatingManagement = New Quiz_RatingManagement()
        Dim currentRating As Double = rating.SelectAVGQuizRatingByQuizId(Request.QueryString("quizId"))

        LikeRating.CurrentRating = Math.Round(currentRating)

        'add ranking
        Dim myPoints As Users_RankingPointsManagement = New Users_RankingPointsManagement()
        Dim rankingPointsId As Int32 = myPoints.SelectRankingPointsByType("Rank Quiz")

        myPoints.InsertUsersRankingPoints(userId, rankingPointsId)
        Catch ex As Exception

        End Try
    End Sub

    Protected Function getName(ByVal name As String, ByVal surname As String, ByVal mydate As String)
        Try

            Return (name + " " + surname + " on " + mydate)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function



    Protected Sub btnAddComment_Click(sender As Object, e As EventArgs) Handles btnAddComment.Click
        Try

        
        Dim myComment As CommentsManagement = New CommentsManagement()
        Dim aCookie As HttpCookie = Request.Cookies("userIdCookie")
        Dim userId = Convert.ToInt32(aCookie.Value)
        Dim myDate As DateTime = DateTime.Now
        myDate = New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)
        myComment.InsertComment(Request.QueryString("quizId"), userId, txtCommentSubmit.Text, myDate, False)

        txtCommentSubmit.Text = ""

        'Ranking
        Dim myPoints As Users_RankingPointsManagement = New Users_RankingPointsManagement()
        Dim rankingPointsId As Int32 = myPoints.SelectRankingPointsByType("Add Comment")

        myPoints.InsertUsersRankingPoints(userId, rankingPointsId)

        lblMessage.Text = "Comment has been submitted. Points Awarded. Please wait for approval by administration"
        Catch ex As Exception

        End Try
    End Sub


    Protected Sub ButtonUnLike_Click(sender As Object, e As EventArgs)
        Try

            Dim aCookie As HttpCookie = Request.Cookies("userIdCookie")
            Dim userId = Convert.ToInt32(aCookie.Value)

            Dim btn As Button = CType(sender, Button)
            Dim myCommentLike As Comments_LikeManagement = New Comments_LikeManagement()
            myCommentLike.DeleteCommentLikeByCommentIdUserId(Convert.ToInt32(btn.CommandName), userId)

            lstViewComments.DataBind()

        Catch ex As Exception

        End Try
    End Sub

    Public Function getButtonId(ByVal commentId As Int32)

        Try

            Dim myCommentCount As Comments_LikeManagement = New Comments_LikeManagement()
            Dim dr2 As OleDbDataReader = myCommentCount.SelectCommentsLikesByCommentId(commentId)
            Dim count As Int32 = 0
            If dr2.HasRows Then
                Do While dr2.Read()
                    count = count + 1
                Loop
            End If

            If (count > 0) Then


                Dim DivLikeId As String = "DivLikeId" + commentId.ToString()

                ltrCode.Text += "<script type=""text/javascript"">"
                ltrCode.Text += "$(document).ready(function () {"
                ltrCode.Text += "$(function () {"
                ltrCode.Text += "$(""[id$=" + DivLikeId + "]"").dialog({"
                ltrCode.Text += "draggable: true,"
                ltrCode.Text += "resizable: false,"
                ltrCode.Text += "show:'blind',"
                ltrCode.Text += "hide:'blind',"
                ltrCode.Text += "width: 350,"
                ltrCode.Text += "autoOpen: false,"
                ltrCode.Text += "minHeight: 40,"
                ltrCode.Text += "minwidth: 10,"
                ltrCode.Text += "zIndex: 2000"
                ltrCode.Text += "});"
                ltrCode.Text += "});"

                Dim lblBtnLikeId As String = "lblBtnLikeId" + commentId.ToString()

                ltrCode.Text += "$(""[id$=" + lblBtnLikeId + "]"").click(function () {"
                ltrCode.Text += "var browsername = navigator.appName;"
                ltrCode.Text += "if (browsername == ""Netscape"") {"
                ltrCode.Text += "$(""#question"").dialog({ modal: true });"
                ltrCode.Text += "}"
                ltrCode.Text += "else {"
                ltrCode.Text += "$('#" + DivLikeId + "').dialog('option', 'position', [event.clientX, event.clientY]);"
                ltrCode.Text += "}"
                ltrCode.Text += "$(""#" + DivLikeId + """).dialog(""open"");"
                ltrCode.Text += "return false;"
                ltrCode.Text += "});"
                ltrCode.Text += "});"
                ltrCode.Text += "</script>"

                ltrUsersLiked.Text += "<div id=""" + Convert.ToString(DivLikeId) + """ title=""Comment Likes"" >"

                Dim myCommentLike As Comments_LikeManagement = New Comments_LikeManagement()

                Dim dr As OleDbDataReader = myCommentLike.SelectCommentsLikesByCommentId(commentId)

                ltrUsersLiked.Text += "<p>"
                ltrUsersLiked.Text += "<table>"
                If dr.HasRows Then
                    Do While dr.Read()

                        ltrUsersLiked.Text += "<tr>"

                        If Not IsDBNull(dr("ProfileName")) Then
                            ltrUsersLiked.Text += "<td>"
                            ltrUsersLiked.Text += "<a href=ProfileViewer.aspx?ProfileId=" + dr("ProfileID").ToString() + "><img width=""50px"" src=""" + dr("ProfileAvatar") + """ /></a>"
                            ltrUsersLiked.Text += "</td>"


                            ltrUsersLiked.Text += "<td>"
                            ltrUsersLiked.Text += "<a href=ProfileViewer.aspx?ProfileId=" + dr("ProfileID").ToString() + ">" + dr("ProfileName").ToString() + " " + dr("ProfileSurname").ToString() + "</a>"
                            ltrUsersLiked.Text += "</td>"



                        End If

                        ltrUsersLiked.Text += "</tr>"

                    Loop

                    ltrUsersLiked.Text += "</table>"
                    ltrUsersLiked.Text += "</p>"
                End If




                ltrUsersLiked.Text += "</div>"
            End If

            Return "lblBtnLikeId" + commentId.ToString()

        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Protected Sub ButtonLike_Click(sender As Object, e As EventArgs)
        Try

        
        Dim aCookie As HttpCookie = Request.Cookies("userIdCookie")
        Dim userId = Convert.ToInt32(aCookie.Value)

        Dim btn As Button = CType(sender, Button)

        Dim myCommentLike As Comments_LikeManagement = New Comments_LikeManagement()
        myCommentLike.InsertCommentLike(Convert.ToInt32(btn.CommandName), userId)

        'add ranking
        Dim myPoints As Users_RankingPointsManagement = New Users_RankingPointsManagement()
        Dim rankingPointsId As Int32 = myPoints.SelectRankingPointsByType("Like Comment")

        myPoints.InsertUsersRankingPoints(userId, rankingPointsId)

        lstViewComments.DataBind()
        Catch ex As Exception

        End Try
    End Sub

    Public Function showLikeButton(ByVal commentId As Int32)
        Try

            Dim myCommentLike As Comments_LikeManagement = New Comments_LikeManagement()

            Dim aCookie As HttpCookie = Request.Cookies("userIdCookie")
            Dim userId = Convert.ToInt32(aCookie.Value)

            Dim count As Int32 = Convert.ToInt32(myCommentLike.SelectCountCommentIdUserId(commentId, userId))

            If (count = 0) Then
                Return True
            Else
                Return False
            End If


        Catch ex As Exception
            Return Nothing
        End Try

    End Function

    Public Sub ListViewComments_ItemDataBound(sender As Object, e As ListViewItemEventArgs)
        Try

            If (e.Item.ItemType = ListViewItemType.DataItem) Then

                Dim commentId As Int32 = DirectCast(DirectCast(e.Item, System.Web.UI.WebControls.ListViewDataItem).DataItem, System.Data.DataRowView).Row.ItemArray(0)
                If (showLikeButton(commentId)) Then

                    e.Item.FindControl("btnLike").Visible = True
                    e.Item.FindControl("lblLikes").Visible = False
                    e.Item.FindControl("btnUnLike").Visible = False

                Else
                    e.Item.FindControl("lblLikes").Visible = True
                    e.Item.FindControl("btnLike").Visible = False
                    e.Item.FindControl("btnUnLike").Visible = True
                End If

            End If



        Catch ex As Exception

        End Try


    End Sub


    Public Function getWhoLiked(ByVal commentId As Int32)
        Try

        

        Dim myCommentLike As Comments_LikeManagement = New Comments_LikeManagement()
        Dim messageOutput As String = String.Empty
        messageOutput = messageOutput + "You and "

        Dim dr As OleDbDataReader = myCommentLike.SelectCommentsLikesByCommentId(commentId)
        Dim count As Int32 = 0
        If dr.HasRows Then
            Do While dr.Read()
                count = count + 1
            Loop

            If (count > 2) Then
                messageOutput = messageOutput + (count - 1).ToString() + " others like this comment"
            ElseIf (count = 2) Then
                messageOutput = messageOutput + (count - 1).ToString() + " other like this comment"
            Else
                messageOutput = "You like this comment"
            End If
        End If

            Return messageOutput
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Protected Sub btnStartQuiz_Click(sender As Object, e As EventArgs) Handles btnStartQuiz.Click
        Try


            Dim numberOfQuestionsSubmitted As Int32 = New Quiz_QuestionManagement().SelectNumberOfQuestionsPerQuiz(Convert.ToInt32(Request.QueryString("quizId")))
            If (numberOfQuestionsSubmitted < 6) Then
                lblQuizError.Text = "Quiz cannot start because there are not enough number of questions"
            Else
                Response.Redirect("~/PlayQuiz.aspx?quizId=" + Request.QueryString("quizId"))
            End If
        Catch ex As Exception

        End Try
    End Sub
End Class